/**
 * @author 太阳当空丶赵
 * @date 2022/12/2-9:44
 * @version 1.0.0
 * getOpenId
 * 获取用户openid
 */
const {wx} = require("../config")
const axios = require("axios")

// code是用户登录凭证
module.exports = function(code) {
    const getTokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wx.AppId}&secret=${wx.AppSecret}&code=${code}&grant_type=authorization_code`
    return new Promise(async (resolve,reject) => {
        try {
            process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
            const codeResult = await axios.get(getTokenUrl)
            // resolve(codeResult)
            //
            const {data} = codeResult
            resolve(data["openid"])
        }catch (e){
            resolve(false)
        }
    })

    // const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wx.AppId}&secret=${wx.AppSecret}&js_code=${code}&grant_type=authorization_code`
    // // const url = `https://api.weixin.qq.com/sns/jscode2session?appid=wx2b1b9f396a67b94c&secret=b76856231c6db17c47e3e88779c95889&js_code=${code}&grant_type=authorization_code`
    // // 无论成功失败都返回一个成功的promise
    // return new Promise(resolve => {
    //     axios.get(url).then(result => {
    //         const {data} = result
    //         if (!data['errcode']){
    //             console.info("success",data)
    //             resolve({openId:data['openid'],sessionKey:data['session_key']})
    //         }else {
    //             console.info("error",data)
    //             resolve(false)
    //         }
    //     }).catch(error => {
    //         console.error("catch",error)
    //         resolve(false)
    //     })
    // })
}

